<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>canvas绘制简单图形和多边形</title>
    <style>
        .content {
            margin: 15px auto;
            width: 800px;
        }
        canvas {
            background: #fafafa;
        }
    </style>
</head>

<body class="body">
    <div class="content">
        <h4>绘制多边形：</h4>
        <canvas id="canvas4" width="800" height="300"></canvas>
    </div>


    <script type="text/javascript">
       
        var can4 = document.getElementById('canvas4');
        var ctx4 = can4.getContext('2d');
        var drawPolygon = function(ctx, conf){
            var x = conf && conf.x || 0;  //中心点x坐标
            var y = conf && conf.y || 0;  //中心点y坐标
            var num = conf && conf.num || 3;   //图形边的个数
            var r = conf && conf.r || 100;   //图形的半径
            var width = conf && conf.width || 5;
            var strokeStyle = conf && conf.strokeStyle;
            var fillStyle = conf && conf.fillStyle;
            //开始路径
            ctx.beginPath();
            var startX = x + r * Math.cos(2*Math.PI*0/num);
            var startY = y + r * Math.sin(2*Math.PI*0/num);
            ctx.moveTo(startX, startY);
            for(var i = 1; i <= num; i++) {
                var newX = x + r * Math.cos(2*Math.PI*i/num);
                var newY = y + r * Math.sin(2*Math.PI*i/num);
                ctx.lineTo(newX, newY);
            }
            ctx.closePath();
            //路径闭合
            if(strokeStyle) {
                ctx.strokeStyle = strokeStyle;
                ctx.lineWidth = width;
                ctx.lineJoin = 'round';
                ctx.stroke();
            }
            if(fillStyle) {
                ctx.fillStyle = fillStyle;
                ctx.fill();
            }
        };
        drawPolygon(ctx4, {
            x: 150,
            y: 150,
        	num: 6,
        	r: 100,
        	strokeStyle: 'blue',
        	fillStyle: '#9da'
        });



    </script>
</body>
</html>